package com.yomob.kylin.support;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.UnknownHostException;

public class IpUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(IpUtil.class);
    private String fileName = "/tmp/GeoLite2-City.mmdb";
    private DatabaseReader reader ;
    public IpUtil() throws IOException, URISyntaxException {
        File database = new File(fileName);
        reader = new DatabaseReader.Builder(database).build();
    }
    /**
    array[0] = city,array[1] = province,array[2] = country
     */
    public String[] getCityInfo(String ip) {
        InetAddress ipAddress = null;
        String[] cityInfo = new String[3];
        try {
            ipAddress = InetAddress.getByName(ip);
            CityResponse response = reader.city(ipAddress);
            cityInfo[0] = response.getCity().getName();
            cityInfo[1] = response.getMostSpecificSubdivision().getName();
            cityInfo[2] = response.getCountry().getName();
        } catch (UnknownHostException e) {
            LOGGER.warn(e.getMessage());
            return null;
        } catch (IOException e) {
            LOGGER.warn(e.getMessage());
            return null;
        } catch (GeoIp2Exception e) {
            LOGGER.warn(e.getMessage());
            return null;
        }
        return cityInfo;
    }
}
